<?php declare(strict_types=1);

namespace App\Services\ElectronicSignature\Strategy;


use App\Exceptions\BizException;
use App\Models\CommonConfigs;
use App\Models\Elec\ElecContracts;
use App\Models\Elec\ElecContractSignatories;
use App\Models\Store;
use App\Models\StoreBank;
use App\Models\StorePayWay;
use App\Services\ElectronicSignature\Exception\ElSignException;
use App\Services\Pay\GuoTonXinYi\Config;
use App\Services\Pay\GuoTonXinYi\SignGt;
use App\Util\RequestUtil;
use App\Util\Rsa\Md5Util;
use App\Vo\ResultVo;
use Illuminate\Support\Facades\Log;
use TencentCloud\Common\Sign;
use function EasyWeChat\Kernel\Support\get_client_ip;

class GtxyElectronicSignatureHandler extends AbstractElectronicSignature
{


    //申请开户
    public function __construct()
    {

    }


    public function getApi(): string
    {
        return "gtxy";
    }

    protected function getConfig(): array
    {
        $config = CommonConfigs::query()->where("config_id", "1234")->first();
        if (empty($config)) {
            
            throw  new \Exception("系统配置参数不存在");
        }
        $config = [
            "agetId" => $config->platform_id,
            "public_key" => $config->public_key
        ];
        return $config;
    }


    /**
     * @return ResultVo
     */
    public function open(Store $store): ResultVo
    {
        $type = $this->getApplyType((string)$store->store_type);
        //结算卡
        $storeBank = StoreBank::query()->where("store_id", $store->store_id)->first();
        if (empty($storeBank) || empty($storeBank->store_bank_no)) {
            throw new \Exception("没有绑定结算卡");
        }
        $validData = [
            "people" => $store->people,
            "head_sfz_no" => $store->head_sfz_no,
            "people_phone" => $store->people_phone,
            "store_name" => $store->store_name,
            "bank_account" => $storeBank->store_bank_no
        ];
        $validator = \Illuminate\Support\Facades\Validator::make($validData, [
            "people" => ["required"],
            "head_sfz_no" => ["required"],
            "people_phone" => ["required"],
            "store_name" => ["required"],
            "bank_account" => ["required"]
        ], [], [
            "people" => "店铺持有人姓名",
            "head_sfz_no" => "身份证号",
            "people_phone" => "联系手机号",
            "store_name" => "店铺名称",
            "bank_account" => "结算卡号"
        ]);
        if ($validator->fails()) {
            throw  new \Exception($validator->errors()->first());
        }


        switch ($type) {
            case "person":
                $reqData = [
                    "custLogin" => $validData["people_phone"],
                    "custName" => $validData["people"],
                    "credNo" => $validData["head_sfz_no"],
                    "phone" => $validData["people_phone"],
                    "accountName" => $validData["people"],
                    "accountNo" => $validData["bank_account"],
                ];
                $signatoryName = $validData["people"];
                $resultVo = SignGt::openPersion($reqData, $this->getConfig());
//                "msg":"个人开户成功！","code":"000000","data":{"userId":"31C497A71862FD1BE0630140840A0BAF"},"success":true}
                break;
            case "company":
                $identNo = $store->store_license_no ?? "";
                $reqData = [
                    "custLogin" => $validData["people_phone"],
                    "enterpriseName" => $validData["store_name"],
                    "identType" => "8",
                    "identNo" => $identNo,
                    "phone" => $validData["people_phone"],
                    "licenseNo" => $identNo,
                    "enterprisePhone" => $validData["people_phone"],
                    "address" => $store->province_name . " " . $store->city_name . " " . $store->area_name . " " . $store->store_address,
                    "transName" => $store->head_name,
                    "transNo" => $validData["head_sfz_no"],
                    "accountName" => $validData["people"],
                    "accountNo" => $validData["bank_account"],
                    "credNo" => $validData["head_sfz_no"],
                    "busName" => $validData["store_name"],
                ];
                $signatoryName = $validData["store_name"];
                $resultVo = SignGt::openCompany($reqData, $this->getConfig());
                break;
            default:
                throw new \Exception("参数异常");
        }
        if ($resultVo->getCode() != 1) {
            throw new BizException($resultVo->getMsg());
        }
        $resultArray = $resultVo->getData();
        //处理Vo
        $response = [
            "user_id" => $resultArray["userId"],
            "signatoryName" => $signatoryName,
            "body" => $resultArray
        ];
        return ResultVo::code("ok")::data($response)::msg($resultVo->getMsg());
    }

    //发送短信
    //通过给用户发送验证码，以验证码授权方式签署合同。验证码有效时间为 10 分钟。
    public function sms(array $param): ResultVo
    {
        $storeArray = $param["storeArray"];
        $type = $this->getApplyType((string)$storeArray["store_type"]);
        switch ($type) {
            case "person":
                $identNo = $storeArray["head_sfz_no"] ?? "";
                break;
            case "company":
                $identNo = $storeArray["store_license_no"] ?? "";
                break;
        }
        if (empty($param["userId"])) {
            throw new \Exception("userId 参数不存在");
        }
        $reqData = [
            "custLogin" => $storeArray["people_phone"],
            "identNo" => $identNo,
            "phone" => $storeArray["people_phone"],
            "isSendVoice" => "0",
            "userId" => $param["userId"],
            "version" => Config::VERSION,
            "timeStamp" => date("YmdHis", time())
        ];

        $resultVo = SignGt::sms($reqData, $this->getConfig());
        if ($resultVo->getCode() != 1) {
            throw new BizException($resultVo->getMsg());
        }
        //设置签约编号
        $response = [
            "randomCode" => $resultVo->getData()["projectCode"]
        ];
        return ResultVo::code("ok")::data($response)::msg($resultVo->getMsg());
    }


    //checkCode
    public function createContract(string $code, array $params = []): ResultVo
    {
        //创建合同-并且校验手机号
        $reqData = [
            "checkCode" => $code,
            "projectCode" => $params["randomCode"],
        ];
        $resultVo = SignGt::checkCode($reqData, $this->getConfig());
        if ($resultVo->getCode() != 1) {
            throw new BizException($resultVo->getMsg());
        }
        //设置签约编号
        $response = [
            "contractNo" => "",
            "contractType" => "",
            "contractTypeName" => "国通标准合同",
            "contractState" => 1,
            "createTime" => date("Y-m-d H:i:s", time()),
            "expiredDate" => null,
            "projectCode" => $params["randomCode"],
            "checkCode" => $code,
        ];
        return ResultVo::code("ok")::data($response)::msg($resultVo->getMsg());
    }

    public function agreeContract(array $params): ResultVo
    {
        return ResultVo::code("ok")::data([])::msg("");
    }

    public function queryContract(array $params): ResultVo
    {
        return ResultVo::code("")::data([])::msg("");
    }

    public function downloadContract(array $params): ResultVo
    {
        return ResultVo::code("")::data([])::msg("");
    }

}